package com.base.doublepoint;

public class SortedSquares {
    /**
     * 977. 有序数组的平方
     * 给你一个按 非递减顺序 排序的整数数组 nums，返回 每个数字的平方 组成的新数组，要求也按 非递减顺序 排序
     */
    public int[] sortedSquares(int[] nums) {
        int[] new_nums = new int[nums.length];
        int mid = -1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] <= 0) {
                mid = i ;
            } else {
                break;
            }
        }

        int left = mid;
        int right = mid + 1;
        int idx = 0;
        while (left > -1 && right < nums.length) {
            if (squares(nums[left]) == squares(nums[right])) {
                new_nums[idx++] = squares(nums[left]);
                new_nums[idx++] = squares(nums[right]);
                left--;
                right++;

            } else if (squares(nums[left]) < squares(nums[right])) {
                new_nums[idx++] = squares(nums[left]);
                left--;
            } else {
                new_nums[idx++] = squares(nums[right]);
                right++;
            }
        }
        while (left > -1) {
            new_nums[idx++] = squares(nums[left--]);
        }
        while (right < nums.length) {
            new_nums[idx++] = squares(nums[right++]);
        }

        return new_nums;
    }

    public int squares(int a) {
        return a * a;
    }

    public static void main(String[] args) {
        int[] nums = {-7,-3,2,3,11};
        SortedSquares sortedSquares = new SortedSquares();
        int[] new_nums = sortedSquares.sortedSquares(nums);
        for (int i = 0; i < new_nums.length; i++) {
            System.out.println(new_nums[i]);
        }

    }
}
